package com.example.jn.checkticketforandroid;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jn.checkticketforandroid.utils.Customer;
import com.example.jn.checkticketforandroid.utils.SPUtils;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;

public class MainActivity extends Activity {

    /*private MediaPlayer mediaPlayer;//MediaPlayer对象*/
    private EditText ip;
    private EditText account;
    private EditText pwd;
    String url;
    String myname;
    String mypwd;
    String gateno;
    private MediaPlayer mp = new MediaPlayer();
    private Button btBind;
    String fileName = "userInfo";        //文件名称


    /*******************karl add 2018-07-04*****************/
    private ProgressBar progressBar;
    private int mProcessStatus = 0;
    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);//全屏显示


        ip = (EditText) findViewById(R.id.ipname);
        account = (EditText) findViewById(R.id.account);
        pwd = (EditText) findViewById(R.id.pwd);
        btBind = (Button) findViewById(R.id.bt_bind);
        url = (String) SPUtils.get(MainActivity.this, Customer.CONFIG_URL, "");
        gateno = (String) SPUtils.get(MainActivity.this, Customer.CONFIG_GATE_NO, "");
        myname = (String) SPUtils.get(MainActivity.this, Customer.CONFIG_ADMIN, "");
        mypwd = (String) SPUtils.get(MainActivity.this, Customer.CONFIG_PASSWORD, "");

        if (!TextUtils.isEmpty(gateno)) {
            //如果不为空
            btBind.setText("已绑定闸机（点击取消绑定）");
        } else {
            btBind.setText("未绑定闸机(登录绑定闸机)");
        }


        if (!TextUtils.isEmpty(url)) {
            ip.setText(url);
        }
        if (!TextUtils.isEmpty(myname)) {
            account.setText(myname);
        }

        if (!TextUtils.isEmpty(mypwd)) {
            pwd.setText(mypwd);
        }

        btBind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 点击 就去取消绑定
                HttpURLRelese();
            }
        });

    }

    public void BtnOnClick(View v) {
        url = ip.getText().toString().trim();
        myname = account.getText().toString().trim();
        mypwd = pwd.getText().toString().trim();

        if (url == null || url.equals("")) {
            System.out.println("请输入地址");
            Toast toast = Toast.makeText(MainActivity.this
                    , "请输入地址"
                    // 设置该Toast提示信息的持续时间
                    , Toast.LENGTH_SHORT);
            toast.show();

            return;
        }
        if (myname == null || myname.equals("")) {

            System.out.println("请输入登陆名");
            Toast toast = Toast.makeText(MainActivity.this
                    , "请输入登陆名"
                    // 设置该Toast提示信息的持续时间
                    , Toast.LENGTH_SHORT);
            toast.show();
            return;
        }
        if (mypwd == null || mypwd.equals("")) {
            System.out.println("请输入登陆密码");
            Toast toast = Toast.makeText(MainActivity.this
                    , "请输入登陆密码"
                    // 设置该Toast提示信息的持续时间
                    , Toast.LENGTH_SHORT);
            toast.show();
            return;
        }

        SPUtils.put(MainActivity.this, Customer.CONFIG_URL, url);
        SPUtils.put(MainActivity.this, Customer.CONFIG_ADMIN, myname);
        SPUtils.put(MainActivity.this, Customer.CONFIG_PASSWORD, mypwd);

        if (gateno == null || gateno.equals("")) {
            HttpURL();
        } else {
            // 如果不为空，那么就直接进入检票
            Intent intent = new Intent(MainActivity.this, CheckTicketActivity.class);
            Bundle bundle = new Bundle();
            /*字符、字符串、布尔、字节数组、浮点数等等，都可以传*/
            bundle.putString("url", url);
            bundle.putString("myname", myname);
            bundle.putString("mypwd", mypwd);
            bundle.putString("gateno", gateno);


            /*把bundle对象assign给Intent*/
            intent.putExtras(bundle);
            startActivity(intent);

//            ShowDialog();
        }

    }

//    private void ShowDialog() {
//        new AlertDialog.Builder(MainActivity.this).setTitle("绑定手持机终端").setMessage("是否取消绑定？")
//                .setPositiveButton("是", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int which) {
//                        HttpURLRelese();
//                    }
//                })
//                .setNegativeButton("否", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int which) {
//                        //提示是否取消绑定
//                        HttpURL();
//                    }
//                })
//                .show();
//    }

    public void BtnOnClickcancle(View v) {
        //退出程序
        android.os.Process.killProcess(android.os.Process.myPid());    //获取PID
        System.exit(0);   //常规java、c#的标准退出法，返回值为0代表正常退出

    }

    //==============================================================调用接口
    private void HttpURL() {
        new Thread() {
            public void run() {
                send();
            }
        }.start();

    }

    public boolean send() {

        try {
            String sendUrl = url + "checkTicketInterface/userLogin.do";

            //1E2147E55DEBE89F795C4BAE81C78890
            System.out.println(sendUrl);
            Map<String, String> map = new HashMap<String, String>();
            map.put("userName", myname);
            map.put("password", mypwd);
            String sign = buildMysign(map, "zmdjfkgudjrhkhssnh");

            SPUtils.put(MainActivity.this, Customer.CONFIG_SING, sign);

            //String sendDate = "userName=admin" + "&password=admin" + "&sign=" + sign;
            String sendDate = "userName=" + myname + "&password=" + mypwd + "&sign=" + sign;

            String result = sendPost(sendUrl, sendDate);
            System.out.println(result);

            if (result.indexOf("<code>0</code>") > 0) {

                if (gateno == null || gateno.equals("")) {
                    Intent intent = new Intent(MainActivity.this, SelectGateActivity.class);

                    /*字符、字符串、布尔、字节数组、浮点数等等，都可以传*/
                    intent.putExtra("url", url);
                    intent.putExtra("myname", myname);
                    intent.putExtra("mypwd", mypwd);
                    /*把bundle对象assign给Intent*/
                    startActivity(intent);
                } else {
                    //提示是否取消绑定
                    Intent intent = new Intent(MainActivity.this, CheckTicketActivity.class);
                    startActivity(intent);
                }
                finish();
            } else {
                String msg = getxmlstr(result, "message");
                System.out.println("test:" + msg);
                showToast(msg);
            }
        } catch (Exception e) {
            showToast("请检查地址配置！");

            return false;
        }
        return true;
    }

    /**
     * 验证消息是否为合法消息
     *
     * @param params 参数数组
     * @param key    接口密钥
     * @return 验证结果
     */
    public static boolean verify(Map<String, String> params, String key) {

        String mysign = buildMysign(params, key);
        String sign = "";
        if (params.get("sign") != null) {
            sign = params.get("sign");
        }
        if (mysign.equals(sign)) {
            return true;
        } else {
            System.out.println("本地签名：" + mysign + " 远程签名：" + sign);
            return false;
        }
    }

    /**
     * 生成签名结果
     *
     * @param sArray 要签名的数组
     * @param key    通知密钥
     * @return 签名结果字符串
     */
    public static String buildMysign(Map<String, String> sArray, String key) {
        try {
            Map<String, String> result = paraFilter(sArray);
            String prestr = createLinkString(result); //把数组所有元素，按照“参数参数值”的模式拼接成字符串
            prestr = key + prestr; //把接口密钥+拼接后的字符串直接连接起来
            String mysign = md5(prestr);
            if (mysign != null) {
                mysign = mysign.toUpperCase();
                System.out.println(mysign);
            }
            return mysign;
        } catch (Exception e) {

        }
        return null;
    }

    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }


    /**
     * @param content
     * @param charset
     * @return
     * @throws UnsupportedEncodingException
     * @throwsSignatureException
     */
    private static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }

        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }

    /**
     * 除去数组中的空值和签名参数
     *
     * @param sArray 签名参数组
     * @return 去掉空值与签名参数后的新签名参数组
     */
    public static Map<String, String> paraFilter(Map<String, String> sArray) {
        Map<String, String> result = new HashMap<String, String>();
        if (sArray == null || sArray.size() <= 0) {
            return result;
        }
        for (String key : sArray.keySet()) {
            String value = sArray.get(key);
            if (value == null || value.equals("") || key.equalsIgnoreCase("sign")) {
                continue;
            }
            result.put(key, value);
        }
        return result;
    }

    /**
     * 把数组所有元素排序，并按照“参数参数值”的模式拼接成字符串
     *
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            prestr = prestr + key + value;
        }
        return prestr;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param sendUrl 发送请求的 URL
     * @param param   请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String sendUrl, String param) {
        try {
            // 发送POST请求
            URL url = new URL(sendUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setConnectTimeout(1000 * 10);
            conn.setReadTimeout(1000 * 20);

            conn.setRequestProperty("Content-Length", "" + param.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(param);
            out.flush();
            out.close();

            // 获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                System.out.println("connect failed!");
                return "";
            }
            // 获取响应内容体
            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return "";
    }

    private static String getString(byte[] b) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            sb.append(b[i]);
        }
        return sb.toString();
    }

    public String getxmlstr(String xml, String resultstr) {
        ByteArrayInputStream tInputStringStream = null;
        String returnstr = "";
        try {
            if (xml != null && !xml.trim().equals("")) {
                tInputStringStream = new ByteArrayInputStream(xml.getBytes());
            }
        } catch (Exception e) {
            return "";
        }
        XmlPullParser parser = Xml.newPullParser();
        try {
            parser.setInput(tInputStringStream, "UTF-8");
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:// 文档开始事件,可以进行数据初始化处理
                        // persons = new ArrayList<Person>();
                        break;
                    case XmlPullParser.START_TAG:// 开始元素事件
                        String name = parser.getName();
                        if (name.equalsIgnoreCase(resultstr)) {
                            returnstr = parser.nextText();
                            System.out.println(returnstr);

                        }
                        break;
                    case XmlPullParser.END_TAG:// 结束元素事件
                        break;
                }
                eventType = parser.next();
            }
            tInputStringStream.close();
            // return persons;

        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return returnstr;
    }
    //======================================================================

    //非UI线程中显示Toast
    public void showToast(String msg) {
        Looper.prepare();//?
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
        Looper.loop();
    }

    //播放音乐的方法
    private void play(String path) {
        try {
            mp.reset();//从新设置要播放的音乐
            mp.setDataSource(path);
            mp.prepare();//预加载音频
            //  mp= MediaPlayer.create(this, R.raw.my);
            mp.start();//播放音乐

        } catch (Exception e) {
            e.printStackTrace();
            Log.e("err", e.getMessage());
        }
        return;
    }

    //播放音乐方法二
    private void myplay() {
        try {
            mp.reset();
            mp.setDataSource("/storage/sdcard1/test.wav");
            mp.prepare();
            mp.start();

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
/*        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.release();
            }
        });*/
        return;
    }


    private void HttpURLRelese() {
        new Thread() {
            public void run() {
                sendRelese();
            }
        }.start();

    }

    public boolean sendRelese() {
        try {
            String sendUrl = url + "checkTicketInterface/gateReleseBound.do";

            System.out.println(sendUrl);
            Map<String, String> map = new HashMap<String, String>();
            map.put("userName", myname);
            map.put("password", mypwd);
            map.put("gateNo", gateno);
            String sign = buildMysign(map, "zmdjfkgudjrhkhssnh");

            String sendDate = "userName=" + myname + "&password=" + mypwd + "&gateNo=" + gateno + "&sign=" + sign;
            String result = sendPost(sendUrl, sendDate);
            System.out.println(result);
            if (result.indexOf("<code>0</code>") > 0) {
                SPUtils.put(MainActivity.this, Customer.CONFIG_GATE_NO, "");
                gateno = "";
                btBind.setText("未绑定闸机(登录绑定闸机)");
//                HttpURL();
                showToast("取消绑定成功！");
            } else if (result.indexOf("<code>50002</code>") > 0) {
                SPUtils.put(MainActivity.this, Customer.CONFIG_GATE_NO, "");
                gateno = "";
                btBind.setText("未绑定闸机(登录绑定闸机)");
//                HttpURL();
                showToast("取消绑定成功！");
            } else {
                String msg = getxmlstr(result, "message");
                System.out.println("test:" + msg);
                showToast(msg);
            }
        } catch (Exception e) {
            showToast("已解绑闸机！");
            return false;
        }
        return true;
    }

    /**
     * 获取内置SD卡路径
     *
     * @return
     */
    public String getInnerSDCardPath() {
        return Environment.getExternalStorageDirectory().getPath();
    }

    public class IniFile {
        /**
         * 点节
         *
         * @author liucf
         */
        public class Section {

            private String name;

            private Map<String, Object> values = new LinkedHashMap<String, Object>();

            public String getName() {
                return name;
            }

            public void setName(String name) {
                this.name = name;
            }

            public void set(String key, Object value) {
                values.put(key, value);
            }

            public Object get(String key) {
                return values.get(key);
            }

            public Map<String, Object> getValues() {
                return values;
            }


        }

        /**
         * 换行符
         */
        private String line_separator = null;

        /**
         * 编码
         */
        private String charSet = "UTF-8";

        private Map<String, Section> sections = new LinkedHashMap<String, Section>();

        /**
         * 指定换行符
         *
         * @param line_separator
         */
        public void setLineSeparator(String line_separator) {
            this.line_separator = line_separator;
        }

        /**
         * 指定编码
         *
         * @param charSet
         */
        public void setCharSet(String charSet) {
            this.charSet = charSet;
        }

        /**
         * 设置值
         *
         * @param section 节点
         * @param key     属性名
         * @param value   属性值
         */
        public void set(String section, String key, Object value) {
            Section sectionObject = sections.get(section);
            if (sectionObject == null)
                sectionObject = new Section();
            sectionObject.name = section;
            sectionObject.set(key, value);
            sections.put(section, sectionObject);
        }

        /**
         * 获取节点
         *
         * @param section 节点名称
         * @return
         */
        public Section get(String section) {
            return sections.get(section);
        }

        /**
         * 获取值
         *
         * @param section 节点名称
         * @param key     属性名称
         * @return
         */
        public Object get(String section, String key) {
            return get(section, key, null);
        }

        /**
         * 获取值
         *
         * @param section      节点名称
         * @param key          属性名称
         * @param defaultValue 如果为空返回默认值
         * @return
         */
        public Object get(String section, String key, String defaultValue) {
            Section sectionObject = sections.get(section);
            if (sectionObject != null) {
                Object value = sectionObject.get(key);
                if (value == null || value.toString().trim().equals(""))
                    return defaultValue;
                return value;
            }
            return null;
        }

        /**
         * 删除节点
         *
         * @param section 节点名称
         */
        public void remove(String section) {
            sections.remove(section);
        }

        /**
         * 删除属性
         *
         * @param section 节点名称
         * @param key     属性名称
         */
        public void remove(String section, String key) {
            Section sectionObject = sections.get(section);
            if (sectionObject != null) sectionObject.getValues().remove(key);
        }


        /**
         * 当前操作的文件对像
         */
        private File file = null;

        public IniFile() {

        }

        public IniFile(File file) {
            this.file = file;
            initFromFile(file);
        }

        public IniFile(InputStream inputStream) {
            initFromInputStream(inputStream);
        }

        /**
         * 加载一个ini文件
         *
         * @param file
         */
        public void load(File file) {
            this.file = file;
            initFromFile(file);
        }

        /**
         * 加载一个输入流
         *
         * @param inputStream
         */
        public void load(InputStream inputStream) {
            initFromInputStream(inputStream);
        }

        /**
         * 写到输出流中
         *
         * @param outputStream
         */
        public void save(OutputStream outputStream) {
            BufferedWriter bufferedWriter;
            try {
                bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, charSet));
                saveConfig(bufferedWriter);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        /**
         * 保存到文件
         *
         * @param file
         */
        public void save(File file) {
            try {
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
                saveConfig(bufferedWriter);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        /**
         * 保存到当前文件
         */
        public void save() {
            save(this.file);
        }

        /**
         * 从输入流初始化IniFile
         *
         * @param inputStream
         */
        private void initFromInputStream(InputStream inputStream) {
            BufferedReader bufferedReader;
            try {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, charSet));
                toIniFile(bufferedReader);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        /**
         * 从文件初始化IniFile
         *
         * @param file
         */
        private void initFromFile(File file) {
            BufferedReader bufferedReader;
            try {
                bufferedReader = new BufferedReader(new FileReader(file));
                toIniFile(bufferedReader);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

        /**
         * 从BufferedReader 初始化IniFile
         *
         * @param bufferedReader
         */
        private void toIniFile(BufferedReader bufferedReader) {
            String strLine;
            Section section = null;
            Pattern p = Pattern.compile("^\\[.*\\]$");
            try {
                while ((strLine = bufferedReader.readLine()) != null) {
                    if (p.matcher((strLine)).matches()) {
                        strLine = strLine.trim();
                        section = new Section();
                        section.name = strLine.substring(1, strLine.length() - 1);
                        sections.put(section.name, section);
                    } else {
                        String[] keyValue = strLine.split("=");
                        if (keyValue.length == 2) {
                            section.set(keyValue[0], keyValue[1]);
                        }
                    }
                }
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        /**
         * 保存Ini文件
         *
         * @param bufferedWriter
         */
        private void saveConfig(BufferedWriter bufferedWriter) {
            try {
                boolean line_spe = false;
                if (line_separator == null || line_separator.trim().equals("")) line_spe = true;
                for (Section section : sections.values()) {
                    bufferedWriter.write("[" + section.getName() + "]");
                    if (line_spe)
                        bufferedWriter.write(line_separator);
                    else
                        bufferedWriter.newLine();
                    for (Map.Entry<String, Object> entry : section.getValues().entrySet()) {
                        bufferedWriter.write(entry.getKey());
                        bufferedWriter.write("=");
                        bufferedWriter.write(entry.getValue().toString());
                        if (line_spe)
                            bufferedWriter.write(line_separator);
                        else
                            bufferedWriter.newLine();
                    }
                }
                bufferedWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
